package com.MyDemo.demo.config;

import com.MyDemo.demo.domain.Order;
import com.MyDemo.demo.enums.OrderEventsEnum;
import com.MyDemo.demo.enums.OrderStatusEnum;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.persist.DefaultStateMachinePersister;
import org.springframework.statemachine.support.DefaultStateMachineContext;

import java.util.EnumSet;

/**
 * 状态机配置
 */
@Configuration
@EnableStateMachine(name = "orderStateMachine")
public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<OrderStatusEnum, OrderEventsEnum> {
    @Override
    public void configure(StateMachineStateConfigurer<OrderStatusEnum, OrderEventsEnum> states) throws Exception {
        states
                .withStates()
                .initial(OrderStatusEnum.CREATE) // 设置初始状态
                .states(EnumSet.allOf(OrderStatusEnum.class));
    }
    @Override
    public void configure(StateMachineTransitionConfigurer<OrderStatusEnum, OrderEventsEnum> transitions) throws Exception {
        transitions
                .withExternal().source(OrderStatusEnum.CREATE).target(OrderStatusEnum.PROCESS)
                .event(OrderEventsEnum.ORDER)
                .and()
                .withExternal().source(OrderStatusEnum.PROCESS).target(OrderStatusEnum.COMPLETE)
                .event(OrderEventsEnum.RECEIVE);
    }

    @Bean
    public DefaultStateMachinePersister persister(){
        return new DefaultStateMachinePersister<>(new StateMachinePersist<Object, Object, Order>() {
            @Override
            public void write(StateMachineContext<Object, Object> context, Order order){

            }

            @Override
            public StateMachineContext<Object, Object> read(Order order) throws Exception {
                return new DefaultStateMachineContext(order.getOrderState(), null, null, null);
            }
        });
    }
}
